package com.sxygsj.baselibrary.activity


import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.tencent.mmkv.MMKV
import java.lang.RuntimeException
import java.lang.ref.WeakReference

/**
 * Author: sxygsj
 * Date: 2021/2/26 15:34
 * Description:基类Activity
 * History:
 */
abstract class BaseActivity :AppCompatActivity(){
    protected lateinit var mmkv:MMKV
    /**
     * 判断当前Activity是否在前台。
     */
    private var isActive: Boolean = false

    /**
     * 当前Activity的实例。
     */
    private var activity: Activity? = null

    /** 当前Activity的弱引用，防止内存泄露  */
    private var weakRefActivity: WeakReference<Activity>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onBeforeCreatView(savedInstanceState)
        activity = this
        weakRefActivity = WeakReference(this)
        ActivityCollector.add(weakRefActivity)
        try {
            mmkv= MMKV.defaultMMKV()!!
        }catch (e: RuntimeException){
            Log.e("mmkv 初始化失败",e.message.toString())
        }

    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        val view= LayoutInflater.from(this).inflate(layoutResID, LinearLayout(this), true)
        //防止导航栏覆盖
        view.setPadding(0,0,0,getNavMenuHeight())
        initData()
    }
    /**
     * 沉浸式状态栏
     */
    protected fun immerseStatusBar(){
        QMUIStatusBarHelper.translucent(this)
    }

    /**
     * 设置状态栏黑色字体图标
     */
    protected fun setStatusBarLightMode(){
        QMUIStatusBarHelper.setStatusBarLightMode(this)
    }

    /**
     * 设置状态栏白色字体图标
     */
    protected fun setStatusBarDarkMode(){
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
    }
    /**
     * 获取状态栏高度
     */
    protected fun getStatusBarHeight():Int{
        return QMUIStatusBarHelper.getStatusbarHeight(this)
    }


    /**
     * 获取虚拟导航栏的高度，无返回0
     */
    private fun getNavMenuHeight():Int{
       return QMUIDisplayHelper.getNavMenuHeight(this)
    }

    abstract fun onBeforeCreatView(savedInstanceState: Bundle?)
    abstract fun initData()

    override fun onResume() {
        super.onResume()
        isActive = true


    }

    override fun onPause() {
        super.onPause()
        isActive = false


    }

    override fun onDestroy() {
        super.onDestroy()
        activity = null
        ActivityCollector.remove(weakRefActivity)


    }
}
